from django.shortcuts import render, HttpResponse, redirect, reverse
from crm import models

from crm.forms import RegForm, CustomerForm, ConsultRecordForm, EnrollmentForm
from utils.pagination import Pagination
# from se_crm import settings
from django.conf import settings
from crm.views.base import ShowList

# def customer_list(request):
#     # 查询所有的客户
#
#
#     if request.path_info == reverse('crm:customer_list'):
#         all_customers = models.Customer.objects.filter(consultant__isnull=True)
#     else:
#         all_customers = models.Customer.objects.filter(consultant=request.user_obj)
#
#     return render(request, 'customer_list.html', {'all_customers': all_customers})


from django.db import transaction


class CustomerList(ShowList):

    def get(self, request):

        # print(request.GET, type(request.GET))
        # print(request.GET.urlencode(), type(request.GET.urlencode()))

        q = self.search(['qq', 'name', 'phone'])

        if request.path_info == reverse('crm:customer_list'):
            all_customers = models.Customer.objects.filter(q, consultant__isnull=True, )
        else:
            all_customers = models.Customer.objects.filter(q, consultant=request.user_obj)

        page = Pagination(request.GET.get('page', 1), all_customers.count(), request.GET.copy(), 2)

        return render(request, 'consultant/customer_list.html',
                      {'all_customers': all_customers[page.start:page.end], 'page_html': page.page_html,
                       'url': reverse('crm:customer_list')})

    def multi_apply(self):
        # 公户变私户
        pk_list = self.request.POST.getlist('pk')

        if len(pk_list) + models.Customer.objects.filter(
                consultant=self.request.user_obj).count() > settings.MAX_CUSTOMER_NUM:
            return HttpResponse('你的客户已超上限，请注意身体')

        try:
            with transaction.atomic():

                # 方式一
                # models.Customer.objects.filter(pk__in=pk_list).update(consultant_id=self.request.session.get('user_id'))
                queryset = models.Customer.objects.filter(pk__in=pk_list, consultant=None).select_for_update()  # 加行级锁

                if len(pk_list) != queryset.count():
                    # 申请的客户已经是别人的私户
                    return HttpResponse('手速太慢，你需要再练一练')
                queryset.update(consultant=self.request.user_obj)
                # 方式二
                # self.request.user_obj.customers.add(*models.Customer.objects.filter(pk__in=pk_list))
        except Exception:
            pass

    def multi_pub(self):
        # 私户变公户
        pk_list = self.request.POST.getlist('pk')
        # 方式一
        # models.Customer.objects.filter(pk__in=pk_list).update(consultant=None)
        # 方式二
        self.request.user_obj.customers.remove(*models.Customer.objects.filter(pk__in=pk_list))


# 增加客户
def customer_add(request):
    form_obj = CustomerForm()
    if request.method == 'POST':
        form_obj = CustomerForm(request.POST)
        if form_obj.is_valid():
            form_obj.save()  # 新增
            return redirect('crm:customer_list')

    return render(request, 'consultant/customer_add.html', {'form_obj': form_obj})


# 编辑客户
def customer_edit(request, pk):
    obj = models.Customer.objects.filter(pk=pk).first()
    form_obj = CustomerForm(instance=obj)
    if request.method == 'POST':
        form_obj = CustomerForm(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()  # 编辑
            return redirect('crm:customer_list')

    return render(request, 'consultant/customer_edit.html', {'form_obj': form_obj})


# 新增和编辑
def customer_change(request, pk=None):
    obj = models.Customer.objects.filter(pk=pk).first()
    form_obj = CustomerForm(instance=obj)
    if request.method == 'POST':
        form_obj = CustomerForm(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()  # 新增 和 编辑
            print(request.GET)
            next = request.GET.get('next')
            print(next)
            if next:
                return redirect(next)
            return redirect('crm:customer_list')
    title = '编辑客户' if pk else '新增客户'
    return render(request, 'consultant/customer_change.html', {'form_obj': form_obj, 'title': title})


class ConsultRecordList(ShowList):

    def get(self, request, customer_id=None, *args, **kwargs):
        q = self.search(['note'])

        if customer_id:
            all_consult_record = models.ConsultRecord.objects.filter(q, customer_id=customer_id,
                                                                     customer__consultant=request.user_obj,
                                                                     delete_status=False)

        else:
            all_consult_record = models.ConsultRecord.objects.filter(q, consultant=request.user_obj,
                                                                     delete_status=False)

        page = Pagination(request.GET.get('page', 1), all_consult_record.count(), request.GET.copy(), 2)

        return render(request, 'consultant/consult_record_list.html',
                      {'all_consult_record': all_consult_record.order_by('-date')[page.start:page.end],
                       'page_html': page.page_html,
                       'url': reverse('crm:customer_list')})


# 新增跟进记录
def consult_record_add(request):
    form_obj = ConsultRecordForm(request)
    if request.method == 'POST':
        form_obj = ConsultRecordForm(request.POST)
        if form_obj.is_valid():
            form_obj.save()
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect('crm:my_customer')

    return render(request, 'form.html', {'form_obj': form_obj, 'title': '新增跟进记录'})


# 编辑跟进记录
def consult_record_edit(request, pk):
    obj = models.ConsultRecord.objects.filter(pk=pk).first()
    form_obj = ConsultRecordForm(instance=obj)
    if request.method == 'POST':
        form_obj = ConsultRecordForm(request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect('crm:my_customer')

    return render(request, 'form.html', {'form_obj': form_obj, 'title': '新增跟进记录'})


# 新增和编辑跟进记录
def consult_record_change(request, pk=None):
    obj = models.ConsultRecord.objects.filter(pk=pk).first()
    form_obj = ConsultRecordForm(request, instance=obj)
    if request.method == 'POST':
        form_obj = ConsultRecordForm(request, request.POST, instance=obj)
        if form_obj.is_valid():
            form_obj.save()
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect('crm:my_customer')

    return render(request, 'form.html', {'form_obj': form_obj, 'title': '新增跟进记录'})


class EnrollmentList(ShowList):

    def get(self, request, customer_id=None, *args, **kwargs):

        if customer_id:
            all_enrollment = models.Enrollment.objects.filter(customer_id=customer_id)
        else:
            all_enrollment = models.Enrollment.objects.filter(customer__consultant=request.user_obj)

        page = Pagination(request.GET.get('page', 1), all_enrollment.count(), request.GET.copy(), 2)

        return render(request, 'consultant/enrollment_list.html',
                      {'all_enrollment': all_enrollment.order_by('-enrolled_date')[page.start:page.end],
                       'page_html': page.page_html,
                       })


def enrollment_change(request, customer_id=None, pk=None):
    obj = models.Enrollment.objects.filter(pk=pk).first()

    form_obj = EnrollmentForm(customer_id, instance=obj)
    if request.method == 'POST':
        form_obj = EnrollmentForm(customer_id, request.POST, instance=obj)

        if form_obj.is_valid():
            form_obj.save()
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect('crm:enrollment_list')

    title = '编辑报名表' if pk else '新增报名表'
    return render(request, 'form.html', {'form_obj': form_obj, 'title': title})


def enrollment_change(request, customer_id=None, pk=None):
    obj = models.Enrollment(customer_id=customer_id) if customer_id else models.Enrollment.objects.filter(pk=pk).first()

    form_obj = EnrollmentForm(instance=obj)
    if request.method == 'POST':
        form_obj = EnrollmentForm(request.POST, instance=obj)

        if form_obj.is_valid():
            form_obj.save()
            next = request.GET.get('next')
            if next:
                return redirect(next)
            return redirect('crm:enrollment_list')

    title = '编辑报名表' if pk else '新增报名表'
    return render(request, 'form.html', {'form_obj': form_obj, 'title': title})

# # 分页
# users = [{'name': 'alex-{}'.format(i), 'pwd': 'alexdsb'} for i in range(1, 306)]
#
#
# def user_list(request):
#     page_obj = Pagination(request.GET.get('page', 1), len(users))
#
#     return render(request, 'user_list.html',
#                   {'users': users[page_obj.start:page_obj.end], 'page_html': page_obj.page_html})
